﻿using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.Configuration;
using System;
using System.Linq;
using Com.Ctrip.Framework.Apollo;
using Com.Ctrip.Framework.Apollo.Enums;

namespace Handday.Erp.Core
{
    /// <summary>
    /// 配置中心扩展
    /// </summary>
    public static class ApolloConfigExtensions
    {
        /// <summary>
        /// 加载配置
        /// </summary>
        public static IConfigurationBuilder LoadApolloAppSettings(this IConfigurationBuilder builder)
        {
            //处理Json配置文件
            HandleJsonFile(builder);

            Console.WriteLine("IConfigurationRoot Build...");
            var apollo = builder.Build().GetSection("Handday.ConfigurationCenter");
            Console.WriteLine("IConfigurationRoot Build Completed.");

            //添加框架Apollo设置
            AddFrameworkApolloSettings(builder, apollo);

            return builder;
        }

        /// <summary>
        /// 添加框架Apollo设置
        /// </summary>
        private static void AddFrameworkApolloSettings(IConfigurationBuilder builder, IConfigurationSection apollo)
        {
            var configServer = apollo["ConfigServer"] ?? string.Empty;
            var apolloBuilder = builder
                .AddApollo(new ApolloOptions
                {
                    AppId = apollo["AppId"],
                    MetaServer = apollo["MetaServer"],
                    ConfigServer = configServer.Split(',', StringSplitOptions.RemoveEmptyEntries),
                    Secret = apollo["Secret"],
                    Cluster = apollo["Cluster"],
                    Env = (Env)Enum.Parse(typeof(Env), apollo["Env"]),
                    Namespaces = new string[6] { "global.settings", "global.mysql", "global.mongodb", "global.redis", "global.cap", "global.logs" }
                })
                .AddDefault();

            var nameSpace = apollo["Namespace"];
            if (!string.IsNullOrEmpty(nameSpace))
            {
                if (!Enum.TryParse(apollo["Format"], out ConfigFileFormat configFileFormat))
                {
                    configFileFormat = ConfigFileFormat.Properties;
                }

                foreach (var ns in nameSpace.Split(","))
                {
                    apolloBuilder.AddNamespace(ns, configFileFormat);
                }
            }
        }

        /// <summary>
        /// 处理Json配置文件
        /// </summary>
        private static void HandleJsonFile(IConfigurationBuilder builder)
        {
            var env = Environment.GetEnvironmentVariable("zztx_hostenv", EnvironmentVariableTarget.Machine);
            if (string.IsNullOrWhiteSpace(env))
            {
                env = Environment.GetEnvironmentVariable("zztx_hostenv");
            }

            var jsonFileName = $"appsettings.{env}.json";
            var jsonConfigurationList = builder.Sources.Where(p => p is JsonConfigurationSource).Select(p => p as JsonConfigurationSource).ToList();
            if (!jsonConfigurationList.Any(p => p.Path == jsonFileName))
            {
                builder.AddJsonFile(jsonFileName, true, false);
            }

            jsonConfigurationList.ForEach(p => p.ReloadOnChange = false);
        }
    }
}
